<?php
// +-------------------------------------------------------------------
// |
// +-------------------------------------------------------------------
// | Copyright (c) 2009-2016 All rights reserved.
// +-------------------------------------------------------------------
namespace Service\Agent;

class Agent extends \Service\Common\BaseModel
{
    protected $name = 'agent';

    const CHECK_STATUS_SUBMIT = 0;//已提交
    const CHECK_STATUS_SUCCESS = 1;//已审核
    const CHECK_STATUS_FAIL = 2;//未通过
    
    const AGENT_LEVEL_COUNTY = 0;//县级代理
    const AGENT_LEVEL_CITY = 1;//市级代理
    

    protected $check_status_label = [
        self::CHECK_STATUS_SUBMIT => '已提交',
        self::CHECK_STATUS_SUCCESS => '已审核',
        self::CHECK_STATUS_FAIL => '未通过',
        
    ];
    
    protected $agent_level_label = [
	    self::AGENT_LEVEL_COUNTY => '县级代理',
	    self::AGENT_LEVEL_CITY => '市级代理', 
    ];
    
    protected $user_agent_level = [
     1,//县级代理状态
     2,//市级代理状态
    ];
   
    //获取记录审核状态
    public function getCheckStatus($id)
    {
    	$check_status = $this->where(['id'=>$id])->getField('check_status');
    	return $check_status;
    }
    
    //审核
    public function examine($data, $id)
    {
    	$data = OE('Util')->validate($data, [
    			'agent.check_status' => 'required;label=审核状态;',
    			'agent.remark' => 'label=备注',
    			]);
    	$check_status = $this->getCheckStatus($id);
    	/* if ($check_status == self::CHECK_STATUS_SUCCESS) {
    		throw new \Exception("已审核的记录无法再次审核");
    	} */
    	$no = $data['agent.check_status'] == self::CHECK_STATUS_SUCCESS ? $this->getAgentNo(6) : '';
    	$update = $this->where([
    			      'id'=>$id
    			   ])->save([
    			   		'check_status'=>$data['agent.check_status'],
    			   		'remark'=>$data['agent.remark'],
    			   		'no' => $no,
    			   		'update_time' => date('Y-m-d H:i:s'),
    			   		]);
    	if($update === false){
    		throw new \Exception("审核失败");
    	}
    	$result = $this->where(['id'=>$id])->find();
    	if ($result['check_status'] == self::CHECK_STATUS_SUCCESS) {
	    	$userUpdate = M('user')->where([
	    			       'uid'=>$result['uid']
	    			    ])->save([
	    			    		'agent_level'=>$this->user_agent_level[$result['level']],
	    			    		]);
	    	if ($userUpdate === false) {
	    		throw new \Exception("更新级别失败");
	    	}
	    	$this->agentCents($id);//执行代理奖金分成
    	}else{
    		$userUpdate = M('user')->where([
    				'uid'=>$result['uid']
    				])->save([
    						'agent_level'=> 0,
    						]);
    		if ($userUpdate === false) {
    			throw new \Exception("更新级别失败");
    		}
    	}
    	return true;
    }
    
    //执行代理结算
    public function agentCents($id)
    {
    	$one_ratio = C('ONE_REFEREE_RATIO')?:0.2;
    	$two_ratio = C('TWO_REFEREE_RATIO')?:0.1;
    	$agent_fee_arr = [
    	     C('LEVEL_COUNTY_MONEY')?:0,
    	     C('LEVEL_CITY_MONEY')?:0,
    	];
    	try {
    		
    		$result = $this->where([
    				'id'=>$id,
    				'check_status'=>self::CHECK_STATUS_SUCCESS
    				])->find();
    		if (!$result) {
    			throw new \Exception('无效的结算记录');
    		}
    		$agentFee = $agent_fee_arr[$result['level']];
    		$this->startTrans();
    		//一级推荐人分成
			$user_detail = O('user')->getUserInfo($result['uid']);
			if($user_detail['referer_id']){
    		    OE('user')->settleAgent($user_detail['referer_id'],$agentFee,$one_ratio,$id);
			
    		    //二级推荐人分成
				$one_user_detail = O('user')->getUserInfo($user_detail['referer_id']);
				if($one_user_detail['referer_id']){
					OE('user')->settleAgent($one_user_detail['referer_id'],$agentFee,$two_ratio,$id);
				}
			}
    		$this->commit();
    	} catch (Exception $e) {
    		$this->rollback();
    		throw new \Exception($e->getMessage());
    	}
    	return true;
    }
    
    
    public function settle($id)
    {
    	try {
	    	$list = $this->where([
	    			     'id'=>$id,
	    			     'is_settle' => 0,
	    			     'check_status' => self::CHECK_STATUS_SUCCESS
	    			])->find();
	    	if (!$list) {
	    		throw new \Exception('无效的结算记录');
	    	}
	    	$logList = M('commission_log')->where([
	    			   'settle_id' => $list['id'],
	    			   'settle_status' => 0,
	    			])->select();
	    	if (!$logList) {
	    		throw new \Exception('无效的结算id：'.$list['id']);
	    	}
	    	$this->startTrans();
	    	foreach ($logList as $v){
	    		OE('user')->settleAgentBounds($v['uid'], $v['money']);
	    		$update = M('commission_log')->where([
	    		                      'id'=>$v['id'],
	    				    ])->save([
	    				    		'settle_status' => 1
	    				    		]);
	    		if ($update === false) {
	    			throw new \Exception('修改佣金记录结算状态失败');
	    		}
	    	}
	    	$save = $this->where([
	    			  'id'=>$list['id']
	    			])->save([
	    			  'is_settle' => 1,
	    			  'update_time' => date('Y-m-d H:i:s'),
	    					]);
	    	if ($save === false) {
	    		throw new \Exception('修改区域代理记录结算状态失败');
	    	}
    	
    	   $this->commit();
    	} catch (Exception $e) {
    		$this->rollback();
    		throw new \Exception($e->getMessage());
    	}
    	return true;
    }
    
    
    //获取申请代理信息
    public function getAgent($uid)
    {
    	$result = $this->where(['uid'=>$uid])->find();
		$user_detail = O('user')->getUserInfo($uid);
    	$refereeInfo = O('user')->getUserInfo($user_detail['referer_id']);
    	$result['referee'] = $refereeInfo['mobile'];
    	$result['level_label'] = $this->agent_level_label[$result['level']];
    	$result['check_status_label'] = $this->check_status_label[$result['check_status']];
    	$result['location_label'] = O('common')->getAreaLabel($result['location']);
    	return $result;
    }
    
    //处理地区
    
    
    public function handleLocation($data)
    {
    	if ($data['level'] == self::AGENT_LEVEL_CITY) {
    		$array = explode(',', $data['location']);
    		$data['location'] = $array[0].','.$array[1];
    	}
    	return $data;
    }
    //申请代理商
    public function applyAgent($data, $uid)
    {
    	$data = OE('Util')->validate($data, [
    			'company' => 'required;label=公司名称',
    			'level' => 'required;label=申请等级;',
    			'business_licence' => 'required;label=营业执照',
    			'location' => 'required;label=申请地区',
    			]);

        $data = $this->handleLocation($data);//处理地区
    	 $count = $this->where([
    			'location'=>$data['location'],
    			])->count();
    	if ($count > 0) {
    		throw new \Exception("您申请的地区已经有代理商了");
    	} 
    	$result = $this->where(['uid'=>$uid])->find();
    	$userInfo = M('user')->where(['uid'=>$uid])->find();
    	if ($result) {
    		if ($result['check_status'] == self::CHECK_STATUS_SUBMIT || $result['check_status'] == self::CHECK_STATUS_SUCCESS) {
    			throw new \Exception("您申请的代理商已经在审核中或已审核通过，无法再次修改申请信息");
    		}
    		$re = $this->where([
    				   'uid'=>$result['uid']
    				   ])->save([
	    			        'level'=>$data['level'],
			    			'check_status'=>self::CHECK_STATUS_SUBMIT,
			    			'location'=>$data['location'],
    				   		'referee_uid'=>$userInfo['referer_id'],
			    			'company'=>$data['company'],
			    			'business_licence'=>$data['business_licence'],
    				   		'update_time'=>date('Y-m-d H:i:s'),
    				   		]); 
    		if ($re === false) {
    			throw new \Exception("修改申请失败");
    		}
    	}else{
	    	$insertId = $this->add([
			    			'uid'=>$uid,
	    			        'level'=>$data['level'],
			    			'check_status'=>self::CHECK_STATUS_SUBMIT,
			    			'location'=>$data['location'],
	    			        'referee_uid'=>$userInfo['referer_id'],
			    			'company'=>$data['company'],
			    			'business_licence'=>$data['business_licence'],
			    			'create_time'=>date('Y-m-d H:i:s'),
			    			]);
	    	
	    	if (!$insertId) {
	    		throw new \Exception("申请失败");
	    	}
    	}
    	return true;
    }
    
    
    public function formatCallback($data)
    {
	
    	$refereeInfo = O('user')->getUserInfo($data['agent.referee_uid']);
    	$total_contribution = $this->getContribution($data['agent.no']);//区域总业绩
    	$month_total_contribution = $this->getContribution($data['agent.no'],date('Y-m-01'),date('Y-m-d'));//当月区域总业绩
    	return [
    	'agent.referee_mobile'=>$refereeInfo['mobile'],//推荐人手机号
    	'agent.referee_real_name'=>$refereeInfo['real_name'],//推荐人姓名
    	//'agent.total_contribution' => $total_contribution,//区域总业绩
    	//'agent.month_total_contribution' => $month_total_contribution,//当月区域总业绩
    	];
    }
    
    public function getContribution($no,$start_time = '',$end_time = '')
    {
    	if (!$no) {
    		return number_format(0,2,'.','');
    	}
    	$where = [
	    	'b.agent_no' => $no,
	    	'a.order_status' => 1,
	    	'a.pay_status' => 1,
    	 ];
    	if ($start_time || $end_time) {
    		if ($start_time) {
    			$where['a.pay_time'][] = ['egt', $start_time . ' 00:00:00'];
    		}
    		if ($end_time) {
    			$where['a.pay_time'][] = ['elt', $end_time . ' 23:59:59'];
    		}
    	}
    	$total_order_contribution = M('order')->alias('a')
    	                                ->join('__USER__ b on b.uid = a.uid')
    	                                ->where($where)
    	                                ->sum('order_contribution');
    	return number_format($total_order_contribution,2,'.','');
    }
    
    public function getAgentNo($num = 5)
    {
    	while (1) {
    		$str = O('util')->rand($num);
    		$count = $this->where(['no' => $str])->count();
    		if ($count) {
    			continue;
    		}
    		return $str;
    	}
    }
    
}